<template>
  <div class="register">
    <div class="regpage">
      <div class="reg reg_email">
        <el-row>
          <el-button type="text"
                     class="phonecs"
                     :class="status == true ? 'btnactive' : ''"
                     @click="status = true">手机注册</el-button>
          <el-button type="text"
                     class="emailcs"
                     :class="status == false ? 'btnactive' : ''"
                     @click="status = false">邮箱注册</el-button>
        </el-row>
        <!-- 手机注册 -->
        <el-form ref="registerPhone"
                 :model="registerPhone"
                 :rules="phoneRule"
                 class="register-form phoneform"
                 v-if="status">
          <!-- 请输入注册角色 -->
          <el-form-item prop="roleType">
            <span class="span">*</span>

            <el-select style="width: 100%"
                       v-model="registerPhone.roleType"
                       placeholder="请选择注册角色">
              <el-option v-for="dict in dict.type.sys_role_type"
                         :key="dict.value"
                         :label="dict.label"
                         :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
          <!-- 姓名 -->
          <el-form-item prop="nickName">
            <span class="span">*</span>
            <el-input v-model="registerPhone.nickName"
                      placeholder="请输入客户姓名"></el-input>
          </el-form-item>
          <!-- 工作单位 -->
          <el-form-item prop="deptName">
            <span class="span">*</span>
            <el-input v-model="registerPhone.deptName"
                      placeholder="请输入工作单位"></el-input>
          </el-form-item>

          <el-form-item v-show="false">
            <span class="span">*</span>
            <el-input v-model="registerPhone.registerType"></el-input>
          </el-form-item>

          <!-- 注册手机号 -->
          <el-form-item prop="phonenumber">
            <span class="span">*</span>
            <el-input v-model.trim="registerPhone.phonenumber"
                      type="text"
                      @input="phonechange"
                      placeholder="请输入注册手机号">
            </el-input>
          </el-form-item>

          <el-form-item prop="code">
            <div style="width: 60%;display:flex;">
              <span class="span">*</span>
              <el-input v-model="registerPhone.code"
                        placeholder="验证码">
              </el-input>
            </div>

            <el-button :class="phonestate?'bgcolor':'bgcolor stop'"
                       :disabled="!phonestate"
                       v-if="!countdown"
                       @click="getCode">
              {{countdown1?"重新发送":"获取验证码"}}
            </el-button>

            <el-button class="bgcolor stop"
                       v-if="countdown"
                       :disabled="true">
              {{countdown}} s
            </el-button>

          </el-form-item>

          <el-checkbox v-model="phonechecked">同意<a href="/"
               style="color: #0b9eae;">《用户协议》</a>及<a href="/"
               style="color: #0b9eae;">《隐私协议》</a></el-checkbox>
          <el-form-item style="width: 100%; margin-top: 35px">
            <el-button :loading="loading"
                       size="medium"
                       style="width: 100%; height: 40px; background-color: #aa2290; color:#fff"
                       @click.native.prevent="handleRegister">
              <span v-if="!loading">注 册</span>
              <span v-else>注 册 中...</span>
            </el-button>
          </el-form-item>
          <div style="float: right">
            <router-link class="link-type"
                         :to="'/userlogin'">已注册,
              <a href="/"
                 style="color: #0b9eae;">去登陆</a>
            </router-link>
          </div>
        </el-form>

        <!-- 邮箱注册 -->
        <el-form ref="registerEmail"
                 :model="registerEmail"
                 :rules="emailRule"
                 class="register-form phoneform"
                 v-show="!status">
          <!-- 请输入注册角色 -->
          <el-form-item prop="roleType">
            <span class="span">*</span>
            <el-select style="width: 100%"
                       v-model="registerEmail.roleType"
                       placeholder="请选择注册角色">
              <el-option v-for="dict in dict.type.sys_role_type"
                         :key="dict.value"
                         :label="dict.label"
                         :value="dict.value"></el-option>
            </el-select>
          </el-form-item>

          <!-- 姓名 -->
          <el-form-item prop="nickName">
            <span class="span">*</span>
            <el-input v-model="registerEmail.nickName"
                      placeholder="请输入客户姓名"></el-input>
          </el-form-item>
          <!-- 工作单位 -->
          <el-form-item prop="deptName">
            <span class="span">*</span>
            <el-input v-model="registerEmail.deptName"
                      placeholder="请输入工作单位"></el-input>
          </el-form-item>

          <el-form-item v-show="false">
            <span class="span">*</span>
            <el-input v-model="registerEmail.registerType"></el-input>
          </el-form-item>

          <!-- 注册邮箱 -->
          <el-form-item class="emsty"
                        prop="email">
            <span class="span">*</span>
            <el-input type="email"
                      v-model="registerEmail.email"
                      placeholder="请输入注册邮箱"
                      autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <span class="span">*</span>
            <el-input type="password"
                      v-model="registerEmail.password"
                      autocomplete="off"
                      placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item prop="checkPass">
            <span class="span">*</span>
            <el-input type="password"
                      v-model="registerEmail.checkPass"
                      autocomplete="off"
                      placeholder="请再次确认密码"></el-input>
          </el-form-item>
          <el-checkbox v-model="emailchecked">
            同意
            <a href="/"
               style="color: #0b9eae;">《用户协议》</a>
            及
            <a href="/"
               style="color: #0b9eae;">《隐私协议》</a>
          </el-checkbox>
          <el-form-item style="width: 100%; margin-top: 35px">
            <el-button :loading="loading"
                       size="medium"
                       style="width: 100%; height: 40px; background-color: #aa2290;color:#fff;"
                       @click.native.prevent="handleRegister">
              <span v-if="!loading">注 册</span>
              <span v-else>注 册 中...</span>
            </el-button>

          </el-form-item>
          <div style="float: right">
            <router-link class="link-type"
                         :to="'/userlogin'">已注册,
              <a href="/"
                 style="color: #0b9eae;">去登陆</a>
            </router-link>
          </div>
        </el-form>
      </div>
    </div>

    <!--  底部  -->
    <div class="el-register-footer">

    </div>
  </div>
</template>

<script>
import { register, isRegister, getCode } from "@/api/register";
export default {
  name: "Register",
  dicts: ['sys_role_type'],
  data () {
    const equalToPassword = (rule, value, callback) => {
      if (this.registerEmail.password !== value) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    return {
      phonestate: false,
      status: true, //true==>手机注册 false==>邮箱注册
      uuid: "",
      registerPhone: {
        roleType: "", //角色
        nickName: "", // 姓名
        deptName: "", // 单位
        phonenumber: "", //手机号
        code: "", //验证码
        registerType: 1,
      },
      phoneRule: {
        phonenumber: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: "手机号格式错误",
            trigger: "blur",
          },
        ],
        roleType: { required: true, message: "注册角色不能为空", trigger: "change" },
        nickName: [{
          required: true, message: "客户姓名不能为空", trigger: "blur",
        }, {
          pattern: /^[\u4E00-\u9FA5]{2,5}$/,
          message: "请输入正确的姓名",
          trigger: "blur",
        }],
        deptName: [
          {
            required: true,
            message: '请输入工作单位',
            trigger: 'blur'
          },
          {
            validator: (rule, value, callback) => {
              // 判断字符长度
              let len = 0;
              for (let i = 0; i < value.length; i++) {
                // 判断字符类型
                if (value[i].match(/[\u4e00-\u9fa5]/)) {
                  len += 2;
                } else {
                  len++;
                }
              }
              if (len < 10 || len > 50) {
                callback(new Error('工作单位长度需在10-50位之间'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          },
          {
            pattern: /^[\u4e00-\u9fa5a-zA-Z0-9()]+$/,
            message: '工作单位只能包含中英文、数字、（）',
            trigger: 'blur'
          }
        ],
        code: { required: true, message: "验证码不能为空", trigger: "blur" },
      },
      registerEmail: {
        roleType: "", //角色
        nickName: "", // 姓名
        deptName: "", // 单位
        email: "", //邮箱
        password: "", //密码
        checkPass: "",//确认密码
        registerType: 2,

      },

      emailRule: {
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 8, max: 30, message: '密码长度在8到30个字符之间', trigger: 'blur' },
          // 正则表达式校验
          {
            pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[-_])[a-zA-Z\d-_]+$/,
            message: '密码必须包含至少一位大小写字母、数字和符号（-、_）',
            trigger: 'blur'
          }
        ],
        checkPass: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 8, max: 30, message: '密码长度在8到30个字符之间', trigger: 'blur' },
          // 正则表达式校验
          {
            pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[-_])[a-zA-Z\d-_]+$/,
            message: '密码必须包含至少一位大小写字母、数字和符号（-、_）',
            trigger: 'blur'
          },
          { required: true, validator: equalToPassword, trigger: "blur" }
        ],
        roleType: { required: true, message: "注册角色不能为空", trigger: "change" },
        nickName: [{
          required: true, message: "客户姓名不能为空", trigger: "blur",
        }, {
          pattern: /^[\u4E00-\u9FA5]{2,5}$/,
          message: "请输入正确的姓名",
          trigger: "blur",
        }],
        deptName: [
          {
            required: true,
            message: '请输入工作单位',
            trigger: 'blur'
          },
          {
            validator: (rule, value, callback) => {
              // 判断字符长度
              let len = 0;
              for (let i = 0; i < value.length; i++) {
                // 判断字符类型
                if (value[i].match(/[\u4e00-\u9fa5]/)) {
                  len += 2;
                } else {
                  len++;
                }
              }
              if (len < 10 || len > 50) {
                callback(new Error('工作单位长度需在10-50位之间'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          },
          {
            pattern: /^[\u4e00-\u9fa5a-zA-Z0-9()]+$/,
            message: '工作单位只能包含中英文、数字、（）',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: "邮箱不能为空", trigger: "blur" },
          {
            pattern: /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/,
            type: "email",
            message: "请输入正确的邮箱格式",
            trigger: ["blur", "change"],

          },
        ],
      },
      emailchecked: false,
      phonechecked: false,
      loading: false,
      captchaEnabled: true,
      countdown: 0,
      countdown1: 0,
    };
  },
  created () {

  },
  methods: {
    phonechange () {
      let reg = /^1[3456789]\d{9}$/
      if (reg.test(this.registerPhone.phonenumber)) {
        isRegister(this.registerPhone).then(res => {
          if (res.code == '200' && res.data > 0) {
            this.phonestate = false
            this.$message.error("该手机号已注册，请登录")
          } else {
            this.phonestate = true
          }
        })
      } else {
        this.phonestate = false
      }
    },
    getCode () {
      if (this.status) {
        var phonenumber = this.registerPhone.phonenumber;
        if (phonenumber == "") {
          this.$modal.msgError("手机号不能为空");
        } else {
          let isPhone = new RegExp("^1[34578][0-90{9}$]", 'i')
          if (isPhone.test(phonenumber)) {
            //调取验证码，先判断手机号是否已经被注册
            isRegister(this.registerPhone).then(response => {
              if (response.code == "200" && response.data == 0) {
                //手机号未被注册，则注册

                getCode(this.registerPhone).then(response => {
                  if (response.code == "200") {
                    this.uuid = response.msg;
                    if (this.countdown === 0) {
                      this.countdown = 60
                      this.countdown1 = 120
                      const timer = setInterval(() => {
                        if (this.countdown > 0) {
                          this.countdown--;
                        } else {
                          clearInterval(timer);
                        }
                      }, 1000);
                      const timer1 = setInterval(() => {
                        if (this.countdown1 > 0) {
                          this.countdown1--;
                        } else {
                          clearInterval(timer1);
                        }
                      }, 1000);
                    }
                    this.$modal.msgSuccess("获取验证码");
                  }
                })
              } else if (response.code == "200" && response.data > 0) {
                this.$modal.msgError("该手机号已注册，请登录");
              }
            })
          } else {
            callback(new Error('请输入正确的手机号码'));
          }
        }
      } else {
        if (this.registerEmail.email == "") {
          this.$modal.msgError("邮箱不能为空不能为空");
        } else {
          //调取验证码，先判断手机号是否已经被注册
          isRegister(this.registerEmail).then(response => {
            if (response.code == "200" && response.data == 0) {
              //手机号未被注册，则注册
              this.$modal.msgSuccess("获取验证码");
              getCode(this.registerEmail).then(response => {
                if (response.code == "200") {
                  this.returnEmailCode = response.msg;
                }
              })
            } else if (response.code == "200" && response.data > 0) {
              this.$modal.msgError("该邮箱已注册，请登录");
            }
          })
        }
      }

    },



    handleRegister () {
      var that = this;
      if (that.status) { //手机注册
        that.$refs.registerPhone.validate((valid) => {
          if (valid) {
            if (!this.phonechecked) {
              this.$message.error("请先阅读用户协议及隐私协议,同意后在进行操作")
              return
            }
            this.loading = true;
            that.registerPhone.uuid = that.uuid;
            register(that.registerPhone)
              .then((res) => {
                const username = this.registerPhone.username;
                this.$alert(
                  "<font color='red'>恭喜你，您的账号 " +
                  this.registerPhone.nickName +
                  " 注册成功！<br> 请耐心等待后台审核，审核通过后将以短信形式通知，界时即可登录! </font>",
                  "系统提示",
                  {
                    dangerouslyUseHTMLString: true,
                    type: "success",
                  }
                )
                  .then(() => {
                    this.$router.push("/userlogin");
                  })
                  .catch(() => { });
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
                if (this.captchaEnabled) {

                }
              });

          }
        });
      } else {
        that.$refs.registerEmail.validate((valid) => {
          if (valid) {
            if (!this.emailchecked) {
              this.$message.error("请先阅读用户协议及隐私协议,同意后在进行操作")
              return
            }
            that.loading = true;
            register(this.registerEmail)
              .then((res) => {
                const email = this.registerEmail.email;
                this.$alert(
                  "<font color='red'>恭喜你，您的账号 " +
                  email +
                  " 注册成功！<br> 请移步邮箱验证并耐心等待后台审核，审核通过后将以邮件形式通知，界时即可登录! </font>",
                  "系统提示",
                  {
                    dangerouslyUseHTMLString: true,
                    type: "success",
                  }
                )
                  .then(() => {
                    this.$router.push("/userlogin");
                  })
                  .catch(() => { });
                that.loading = false;
              })
              .catch(() => {
                this.loading = false;
                if (this.captchaEnabled) {

                }
              });
          }
        });
      }

    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss">
.register {
  width: 100%;
  display: flex;
  // justify-content: center;
  align-items: center;
  height: 100%;
  overflow: hidden;
  .regpage {
    height: 100%;
    flex: 1;
    // background: url("../assets/images/userlogin-page810.png") no-repeat;
    background: url("../assets/images/login.png") no-repeat;
    background-size: 100% 100%;
  }
  .reg {
    width: 420px;
    height: 508px;
    padding: 40px 38px 53px 40px;
    position: absolute;
    top: 128px;
    right: 128px;
    background-color: #fff;
  }
  .reg_email {
    width: 420px;
    height: 546px;
    padding: 40px 38px 53px 40px;
    position: absolute;
    top: 128px;
    right: 128px;
    background-color: #fff;
    .el-button--text {
      color: #000;
    }
    .btnactive {
      font-size: 20px;
      font-family: Source Han Sans CN-Bold, Source Han Sans CN;
      font-weight: bold;
      color: #aa2290;
    }
  }
}
.register-form {
  border-radius: 6px;
  // background: #ffffff;
  width: 340px;
  .el-input {
    height: 40px;
    input {
      height: 40px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
  .bgcolor {
    width: 102px;
    height: 40px;
    background: #aa2290;
    border-radius: 4px 4px 4px 4px;
    // opacity: 1;
    padding: 9px 11px 7px;
    line-height: 1;
    border: none;
    color: #fff;
  }
  .stop {
    background: #ccc;
    color: #fff;
  }
  .el-button.is-disabled {
    background: #ccc;
    color: #fff;
  }
}

.phoneform {
  .el-form-item__content {
    display: flex;
    justify-content: space-between;

    .span {
      margin-right: 10px;
      display: flex;
      align-items: center;
      color: red;
    }
  }
  .el-form-item__content::before,
  .el-form-item__content::after {
    content: none;
  }
}

.regbtn {
  width: 100%;
  height: 40px;
  box-sizing: border-box;
  background: none;
  background-color: #aa2290;
}

// 多选框
.el-checkbox__inner {
  border-radius: 50%;
  .el-checkbox__label {
    a,
    a:focus,
    a:hover {
      cursor: pointer;
      color: aqua;
      text-decoration: none;
    }
  }
}

// 底部按钮
.el-register-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  background-color: #fff;
  letter-spacing: 1px;
  margin-top: 20px;
  font-size: 16px;
  font-family: 806 Typography-806 Typography, 806 Typography;
  font-weight: normal;
  color: #8c8c8c;
}
.el-form-item {
  margin-bottom: 20px;
}
.link-type {
  font-size: 14px;
}
.el-message-box {
  width: 500px;
}
</style>
